<template>
  <el-drawer
    v-model="showDrawer"
    :title="$t(`${from === 'records' ? '订单详情' : '提交成功'}`)"
    size="35%"
    @close="emit('close')"
  >
    <el-card v-loading="loading">
      <div class="detailRow">
        <span class="rowName">{{ $t("订单状态") }}</span>
        <el-tag :type="getOrderStatusName(info.status)?.type">{{
          getOrderStatusName(info.status)?.name
        }}</el-tag>
      </div>
      <div>
        <div class="detailRow">
          <div class="rowName">
            <img
              :src="info.from_icon"
              style="width: 1.25rem; height: 1.25rem"
            />
            <span>{{ info.from_coin_name }}</span>
          </div>

          <span>{{ info.from_quantity }}</span>
        </div>
        <el-icon style="color: #f56c6c"><Bottom /></el-icon>
        <div class="detailRow">
          <div class="rowName">
            <img :src="info.to_icon" style="width: 1.25rem; height: 1.25rem" />
            <span>{{ info.to_coin_name }}</span>
          </div>

          <span>{{ info.to_quantity }}</span>
        </div>
      </div>
      <div
        v-for="(item, index) in infoDetailList"
        :key="index"
        class="detailRow"
        v-show="item.isShow"
      >
        <span class="rowName">{{ item.name }}</span>
        <span class="rowValue">{{ item.value }}</span>
      </div>
    </el-card>
    <!-- 接收视角才显示余额 -->
    <el-card
      v-if="info.ent && [0, 2].includes(info.status)"
      style="margin-top: 1.25rem"
    >
      <div class="detailRow">
        <span class="rowName">{{ $t("余额") }}</span>
        <span class="rowValue">{{ info.balance }}</span>
      </div>
      <div class="detailRow">
        <span class="rowName">{{ $t("剩余时间") }}</span>
        <span class="rowValue">{{ countDownName }}</span>
      </div>
    </el-card>
    <div
      v-if="[0, 2].includes(info.status)"
      class="flex justify-between p-2"
      style="width: 100%; margin-top: 1.25rem"
    >
      <el-button
        v-for="(item, index) in setOrderBtnList"
        :key="index"
        style="width: 100%"
        size="large"
        :plain="item.isPlain"
        :type="item.key === 'cancel' ? 'info' : 'primary'"
        @click="item.click()"
      >
        {{ $t(item.name) }}
      </el-button>
    </div>
  </el-drawer>
</template>
<script setup>
import { ref, reactive, watch, computed, onBeforeUnmount } from "vue";
import {
  getSwapOrderDetailApi,
  postSwapOrderOperationApi,
} from "@/api/swap/index";
import { useI18n } from "vue-i18n";
import _ from "lodash";
import { dayjs } from "element-plus";
import { useStatusStore } from "@/store/modules/status";
import { useRouter } from "vue-router";
const router = useRouter();
const { t } = useI18n();
const statusStore = useStatusStore();
const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  orderNo: {
    type: String,
    default: "",
  },
  from: {
    type: String,
    default: "records",
  },
});
const emit = defineEmits(["close"]);
const showDrawer = ref(false);
const info = reactive({});
const loading = ref(true);
const infoDetailList = computed(() => {
  let arr = [
    { name: "订单号", value: info.order_no, isShow: true },
    {
      name: "价格",
      value: `1 ${info.from_coin_name} = ${info.price} ${info.to_coin_name}`,
      isShow: true,
    },
    { name: "数量", value: info.real_quantity },
    {
      name: `平台手续费(${info.free ? 0 : info.fee_ratio}%)`,
      value: `${info.free ? 0 : info.fee}`,
      isShow: true,
    },
    {
      name: `商户手续费(${info.order_fee_ratio}%)`,
      value: `${info.order_fee}`,
      isShow: info.status !== 0,
    },
    {
      name: "提交时间",
      value: dayjs(info.create_time * 1000).format("YYYY-MM-DD HH:mm:ss"),
      isShow: true,
    },
  ];

  return arr;
});
watch(
  () => props.show,
  (val) => {
    showDrawer.value = val;
  }
);
watch(
  () => props.orderNo,
  (val) => {
    if (val) {
      getOrderInfo(val);
    }
  },
  { immediate: true }
);

const getOrderInfo = async (orderNo) => {
  try {
    loading.value = true;
    const orderInfoRes = await getSwapOrderDetailApi({ order_no: orderNo });
    for (const item in orderInfoRes) {
      info[item] = orderInfoRes[item];
    }
    if ([0, 2].includes(info.status)) {
      countDown();
    }
    loading.value = false;
  } catch (e) {
    loading.value = false;

    console.log(e);
  }
};

const getOrderStatusName = (status) => {
  if (status > -1) {
    return statusStore.swapOrderStatus.find((i) => status === i.key);
  }
};

const setOrderBtnList = computed(() => {
  let btnList = ref([]);
  if (info.ent) {
    btnList.value = [
      {
        key: `${info.status === 0 ? "refuse" : "refuse"}`,
        name: `${info.status === 0 ? "拒绝" : "取消交易"}`,
        isPlain: true,
        click: () => {
          setOrderStatus(info.status === 0 ? "refuse" : "cancel");
        },
      },
      {
        key: `${
          info.status === 0
            ? "accept"
            : info.balance > info.to_quantity
            ? "confirm"
            : "topUp"
        }`,
        name: `${
          info.status === 0
            ? "接单"
            : info.balance > info.to_quantity
            ? "确认交易"
            : "充值"
        }`,
        isPlain: false,
        click: () => {
          setOrderStatus(
            info.status === 0
              ? "accept"
              : info.balance > info.to_quantity
              ? "confirm"
              : "topUp"
          );
        },
      },
    ];
  } else {
    btnList.value = [
      {
        key: `cancel`,
        name: `取消订单`,
        isPlain: true,
        click: () => {
          setOrderStatus("cancel");
        },
      },
    ];
  }
  return btnList.value;
});

// 操作订单（拒绝，接收。。。）
const setOrderStatus = async (type) => {
  try {
    // 如果余额不够则跳转到充值页面
    if (type === "topUp") {
      return router.replace("account/recharge");
    }
    const res = await postSwapOrderOperationApi({
      type,
      order_no: info.order_no,
    });
    if (res) {
      emit("close", "refresh");
    }
    if (res) {
      getOrderInfo(info.order_no);
    }
  } catch (e) {
    console.log(e);
  }
};

// 倒计时处理
const timer = ref(null);
const countDownName = ref("");
const countDown = () => {
  if (timer.value) {
    clearInterval(timer.value);
  }
  let diffTime = (info.expire_time - info.ts) * 1000;
  if (diffTime > 0) {
    timer.value = setInterval(() => {
      diffTime = diffTime - 1000;
      countDownName.value = dayjs(diffTime).format("hh:mm:ss");
    }, 1000);
  } else {
    clearInterval(timer.value);
    item.status = 3;
  }
};
onBeforeUnmount(() => {
  clearInterval(timer.value);
});
</script>
<style lang="scss">
.detailRow {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 0.5rem;

  .rowName {
    min-width: 30%;
    flex-shrink: 0;
    display: flex;
    align-items: center;
  }

  .rowValue {
    word-break: break-all;
    text-align: right;
  }
}
</style>
